package com.example.star.view.center;

import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.star.R;
import com.example.star.adapter.SongAdapter;
import com.example.star.api_service.SongApi;
import com.example.star.entity.Song;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.MusicUploadUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UploadSongActivity extends AppCompatActivity {

    private EditText songNameEdit;
    private EditText singerNameEdit;
    private Button selectSongButton;
    private Button uploadButton;
    private Button getAllSongsButton;
    private Button playButton;
    private Button prevButton;
    private Button nextButton;
    private MediaPlayer mediaPlayer;
    private String currentFilePath;
    private ListView songListView;
    private SongAdapter songAdapter;
    private List<Song> songList = new ArrayList<>();
    private MusicUploadUtils musicUploadUtils;
    private SeekBar seekBar;
    private TextView currentTimeTextView;
    private TextView totalTimeTextView;
    private TextView songInfoTextView;
    private Handler handler = new Handler();
    private int currentSongIndex = 0; // 当前播放歌曲的索引
    private Song selectedSong; // 新增：保存选择的歌曲

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_song);

        songNameEdit = findViewById(R.id.songname_edittext);
        singerNameEdit = findViewById(R.id.singername_edittext);
        selectSongButton = findViewById(R.id.select_song_button);
        uploadButton = findViewById(R.id.upload_button);
        getAllSongsButton = findViewById(R.id.get_all_songs_button);
        playButton = findViewById(R.id.play_button);
        prevButton = findViewById(R.id.prev_button);
        nextButton = findViewById(R.id.next_button);
        songListView = findViewById(R.id.song_list_view);
        seekBar = findViewById(R.id.seek_bar);
        currentTimeTextView = findViewById(R.id.current_time_textview);
        totalTimeTextView = findViewById(R.id.total_time_textview);
        songInfoTextView = findViewById(R.id.song_info_textview);

        songAdapter = new SongAdapter(this, songList);
        songListView.setAdapter(songAdapter);

        // 初始化 MusicUploadUtils
        musicUploadUtils = new MusicUploadUtils(this);

        // 为列表项添加点击监听器，用于选择音乐播放
        songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentSongIndex = position;
                Song selectedSong = songList.get(position);
                String filePath = getFilePathFromSong(selectedSong);
                if (filePath != null) {
                    currentFilePath = filePath;
                    playMusic();
                } else {
                    Toast.makeText(UploadSongActivity.this, "无法获取该歌曲的文件路径", Toast.LENGTH_SHORT).show();
                }
            }
        });

        selectSongButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicUploadUtils.startMusicUpload();
            }
        });

        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedSong != null) {
                    checkAndUploadSong(selectedSong.getMusicData());
                } else {
                    Toast.makeText(UploadSongActivity.this, "请先选择歌曲", Toast.LENGTH_SHORT).show();
                }
            }
        });

        getAllSongsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSongs();
            }
        });

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        playButton.setText("播放");
                    } else {
                        mediaPlayer.start();
                        playButton.setText("暂停");
                    }
                } else {
                    playMusic();
                }
            }
        });

        prevButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentSongIndex > 0) {
                    currentSongIndex--;
                    Song prevSong = songList.get(currentSongIndex);
                    currentFilePath = getFilePathFromSong(prevSong);
                    playMusic();
                } else {
                    Toast.makeText(UploadSongActivity.this, "已经是第一首歌曲", Toast.LENGTH_SHORT).show();
                }
            }
        });

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentSongIndex < songList.size() - 1) {
                    currentSongIndex++;
                    Song nextSong = songList.get(currentSongIndex);
                    currentFilePath = getFilePathFromSong(nextSong);
                    playMusic();
                } else {
                    Toast.makeText(UploadSongActivity.this, "已经是最后一首歌曲", Toast.LENGTH_SHORT).show();
                }
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    private void playMusic() {
        if (currentFilePath != null) {
            File file = new File(currentFilePath);
            if (file.exists()) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(currentFilePath);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    playButton.setText("暂停");
                    seekBar.setMax(mediaPlayer.getDuration());
                    updateSeekBar();
                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            // 播放完一首歌曲后自动播放下一首
                            currentSongIndex++;
                            if (currentSongIndex < songList.size()) {
                                Song nextSong = songList.get(currentSongIndex);
                                currentFilePath = getFilePathFromSong(nextSong);
                                playMusic();
                            } else {
                                // 播放完最后一首歌曲，停止播放
                                mediaPlayer.stop();
                                mediaPlayer.release();
                                mediaPlayer = null;
                                playButton.setText("播放");
                            }
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(UploadSongActivity.this, "播放失败，文件格式可能不支持", Toast.LENGTH_SHORT).show();
                    if (mediaPlayer != null) {
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                }
            } else {
                Toast.makeText(UploadSongActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(UploadSongActivity.this, "请先选择要播放的歌曲", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateSeekBar() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer != null) {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    seekBar.setProgress(currentPosition);
                    currentTimeTextView.setText(formatTime(currentPosition));
                    totalTimeTextView.setText(formatTime(mediaPlayer.getDuration()));
                    handler.postDelayed(this, 1000);
                }
            }
        }, 1000);
    }

    private String formatTime(int time) {
        int totalSeconds = time / 1000;
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        musicUploadUtils.onActivityResult(requestCode, resultCode, data);
        String selectedMusicPath = musicUploadUtils.getSelectedMusicPath();
        if (selectedMusicPath != null) {
            currentFilePath = selectedMusicPath;
            selectedSong = getSongInfoFromFile(selectedMusicPath);
            if (selectedSong != null) {
                showSongInfo(selectedSong);
            } else {
                Toast.makeText(this, "无法获取歌曲信息", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        musicUploadUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void checkAndUploadSong(String filePath) {
        if (validateInput()) {
            SongApi songApi = ApiClient.getSongApi();
            Call<Boolean> call = songApi.checkSongName(selectedSong.getSongname());
            call.enqueue(new Callback<Boolean>() {
                @Override
                public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                    if (response.isSuccessful()) {
                        boolean isSongNameExists = response.body();
                        if (isSongNameExists) {
                            Toast.makeText(UploadSongActivity.this, "歌曲名已存在，不能再次上传", Toast.LENGTH_SHORT).show();
                        } else {
                            uploadSong(filePath);
                        }
                    } else {
                        Toast.makeText(UploadSongActivity.this, "检查歌曲名失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Boolean> call, Throwable t) {
                    Toast.makeText(UploadSongActivity.this, "检查歌曲名时网络错误，请重试", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void uploadSong(String filePath) {
        SongApi songApi = ApiClient.getSongApi();
        Call<Song> saveCall = songApi.saveSong(selectedSong);
        saveCall.enqueue(new Callback<Song>() {
            @Override
            public void onResponse(Call<Song> call, Response<Song> saveResponse) {
                if (saveResponse.isSuccessful()) {
                    Toast.makeText(UploadSongActivity.this, "歌曲信息保存成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(UploadSongActivity.this, "歌曲信息保存失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Song> call, Throwable t) {
                Toast.makeText(UploadSongActivity.this, "保存歌曲信息时网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getSongs() {
        SongApi songApi = ApiClient.getSongApi();
        Call<List<Song>> call = songApi.getAllSongs();
        call.enqueue(new Callback<List<Song>>() {
            @Override
            public void onResponse(Call<List<Song>> call, Response<List<Song>> response) {
                if (response.isSuccessful()) {
                    songList.clear();
                    songList.addAll(response.body());
                    songAdapter.notifyDataSetChanged();
                    if (songList != null) {
                        Toast.makeText(UploadSongActivity.this, "获取到 " + songList.size() + " 首歌曲", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(UploadSongActivity.this, "未获取到歌曲", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(UploadSongActivity.this, "获取歌曲列表失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<Song>> call, Throwable t) {
                Toast.makeText(UploadSongActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacksAndMessages(null);
    }

    private String getFilePathFromSong(Song song) {
        return song.getMusicData(); // 需要根据实际情况修改
    }

    private void showSongInfo(Song song) {
        String info = "歌曲名: " + song.getSongname() + "\n歌手名: " + song.getSingername();
        songInfoTextView.setText(info);
    }

    private boolean validateInput() {
        // 校验明星姓名是否为空
        if (TextUtils.isEmpty(songNameEdit.getText().toString())) {
            Toast.makeText(this, "歌曲名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(singerNameEdit.getText().toString())) {
            Toast.makeText(this, "歌手名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private Song getSongInfoFromFile(String filePath) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            String songName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
            String singerName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);

            if (songName == null) {
                songName = "未知歌曲";
            }
            if (singerName == null) {
                singerName = "未知歌手";
            }

            Song song = new Song();
            song.setSongname(songName);
            song.setSingername(singerName);
            song.setMusicData(filePath);
            return song;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                retriever.release();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}